<?php

/**
 * 默认控制器
 */
class Controller_Shopapi extends Controller_Abstract
{
    function actionIndex()
    {
        try{
            switch($this->_context->server('HTTP_CMSTORE_API_CALL_NAME')){
                case 'TEST': 
                    //如 上传商品 
                    // 解晰 xml
                    // 解晰 数据  
                    // 判断要进行的操作 , 保存 数据
                case 'GetSessionID':
                    $api=new cmshopapi_GetSessionID();
                    break;
                case 'GetToken':
                    $api=new cmshopapi_GetToken();
                    break;
                case 'GetTags':
                    $api=new cmshopapi_GetTags();
                    break;
                case 'GetCategories':
                    $api=new cmshopapi_GetCategories();
                    break;                    
                case 'AddItem':
                    $api=new cmshopapi_AddItem();
                    break;
                default:die('No found this api');
            }
            // 验证 与执行 
            if($api->xmlrequest()){
                $r=$api->Request();
            }
        }catch(Exception_ApiClientInvalidate $ex){
            $apibase=new cmshopApi_base();
            $r=$apibase->xmlresponse(array(
                'Ack'=>'Failure',
                'timestamp'=>$apibase->datetime(),
                'Error'=>' Api client  App Error. Print:'.print_r($ex,true),
            ));
        }catch(Exception_AuthTokenInvalidate $ex){
            dump($ex);
            $apibase=new cmshopApi_base();
            $r=$apibase->xmlresponse(array(
                'Ack'=>'Failure',
                'timestamp'=>$apibase->datetime(),
                'Error'=>' user token Error.',
            ));
        }catch(Exception_RequestFormatInvalidate $ex){
             dump($ex);
             $apibase=new cmshopApi_base();
            $r=$apibase->xmlresponse(array(
                'Ack'=>'Failure',
                'timestamp'=>$apibase->datetime(),
                'Error'=>'  request data format error. ',
            ));
        }catch(Exception $ex){
            $apibase=new cmshopApi_base();
            $r=$apibase->xmlresponse(array(
                'Ack'=>'Failure',
                'timestamp'=>$apibase->datetime(),
                'Error'=>' Any Error. '.print_r($ex,true),
            ));
        }
        Helper_tlog::tofile('shopapi_return.txt',$r);
        die($r); //Warning
    }
 
//     /**
//      * 验证  App 应用的  是否有效     
//      */    
//     function _checkApp(){
//         $app=$this->_context->server('HTTP_CMSTORE_API_APP_NAME');
//         $cert=$this->_context->server('HTTP_CMSTORE_API_CERT_NAME');
//         $this->call=$this->_context->server('HTTP_CMSTORE_API_CALL_NAME');
//         $input=file_get_contents('php://input');
//         Helper_tlog::tofile('shopapi.txt',array('app'=>$app,'cert'=>$cert,'call'=>$this->call));
//         Helper_tlog::tofile('shopapi.txt',$input);
//         // 关键 字段 不能为空.
//         if(!(strlen($app)&&strlen($cert)&&strlen($this->call)&&strlen($input))){
//             return false;
//         }
//         /// 解析  xml 不能出错 .
//         // 验证 xml , 首字段的  名称,属性 
//         $responseDoc = new DomDocument();
// 		$responseDoc->loadXML($input);
// 		$xml=$responseDoc->getElementsByTagName($this->call.'Request');
// 		if($xml->item(0)->getAttribute('xmlns')!='cmshop:apis:shopapi'){
//             return false;
//         }
//         $this->input=Helper_xml::xmlparse($xml);
//         $this->input=$this->input[$this->call.'Request'];
//         // 解析 是否成功 .
//         if(empty($this->input)) return false;
//         //应用是合法的  , 在数据库中 可 找到.  
//         $appclient=Appclient::find('app_name=? And app_cert=? And status&1',$app,$cert)->getOne();
//         if($appclient->isNewRecord()){ return false;}
//         $this->appclient=$appclient->toArray();
//         return $this->appclient['app_id'];
//     }
    // 
    
    /**
     * 取得  token
     */
    function actionToken(){
        $this->_view['sessionid']=$sessionid=$this->_context->sessionid;
        $s=Sessionid::find('sessionid=? And hardexpirationtime>=?',$sessionid,CURRENT_TIMESTAMP)->getOne();
          // 1,app
          
        $this->_view['app']=$app=Appclient::find('app_id=?',$s->app_id)->getOne();
        do{
            if($s->isNewRecord()){
                $this->_view['error']['sessionid']=1;
                break;
            }
            if($app->isNewRecord()){
                $this->_view['error']['app']=1;
                break;
            }
        if($this->_context->isPost()){
        

            //2 ,seller 
            $seller=Sellers::find('seller_name =? And password=?',$this->_context->seller_name,md5($this->_context->password))->getOne();
            if($seller->isNewRecord()){
                $this->_view['error']['seller']=1;
                break;
            }
            //3 ,Domain 
            $domain=Store_Domain::find('domain =? ',$this->_context->domain)->getOne();
            if($domain->isNewRecord()){
                $this->_view['error']['domain']=1;
                break;
            }
            //4 , store
            $store=Stores::find('store_id=?',$domain->store_id)->getOne();
            if($store->isNewRecord()){
                $this->_view['error']['store']=1;
                break;
            }
            //5,
            if($store->seller_id!=$seller->seller_id){
                $this->_view['error']['storeseller']=1;
                break;
            }
            // 6, 生成 token  
            $api_token=new cmshopapi_GetToken();
            $t=$api_token->_lengcode($app->app_id.'_'.$seller->seller_name.'_'.$seller->password,16,'time').'-'.
                $api_token->_lengcode($app->app_id.'_'.$domain->domain.'_'.$store->store_id,16,'time').'-'.
                $api_token->_lengcode($app->app_name,16,'time');
            //7, 保存 session
            $s->data=$t;
            $s->save();
            //8, 保存 token 
            $token=Token::find('app_id=? And seller_id=? And store_id=? ',$app->app_id,$seller->seller_id,$store->store_id)->getOne();
            $token->token=$t;
            $token->hardexpirationtime=time()+15552000;
            if($token->isNewRecord()){
                $token->app_id=$app->app_id;
                $token->seller_id=$seller->seller_id;
                $token->store_id=$store->store_id;
            }
            $token->save();
            $this->_view['token']=$token;
            $this->_view['return']['token']=$token->token;
        }
        }while(0);
    }
//     // 添加产品
//     function _additem(){
//         
//     }
//     //修改产品 , 包括 上下架 
//     function _updateitem($input){
//         
//     }

    /**
     * 创建 店铺 
     */         
    function actionCreateStore(){
        if($this->_context->isPost()){
            do{
                if($this->_context->post('password')!=$this->_context->post('password2')){
                    $this->_view['error']['password']=1;
                    break;
                }
                foreach(array('password','store_name','seller_name','seller_email','currency','language','title') as $k){
                    if(strlen($this->_context->post($k))<=0){
                        $this->_view['error']['null']=1;
                        break 2;
                    }
                }
                $seller=Sellers::find('seller_name=?',$this->_context->post('seller_name'))->getOne();
                $store=Stores::find('name=?',$this->_context->post('store_name'))->getOne();
                $domain=Store_Domain::find('domainprefix=?',$this->_context->post('store_name'))->getOne();
                //$domain=Store_Domain::find('domainprefix=? Or domain=?',$this->_context->post('domainprefix'),$this->_context->post('domain'))->getOne();
                if($seller->isNewRecord()&&$store->isNewRecord()&&$domain->isNewRecord()){
                     // seller
                    $seller->seller_name=$this->_context->post('seller_name');
                    $seller->password=md5($this->_context->post('password'));
                    $seller->save();
                    // store
                    $store->seller_id=$seller->seller_id;
                    $store->name=$this->_context->post('store_name');
                    $store->currency=$this->_context->post('currency');
                    $store->language=$this->_context->post('language');
                    $store->title=$this->_context->post('title');
                    $store->desc=$this->_context->post('desc');
                    $store->layout='ashop'; //$this->_context->post('layout');
                    $store->save();
                    
                    if(strlen($store->store_id)<=0){
                        $this->_view['error']['store']=1;
                        break;
                    }
                    //domain
                    $domain->store_id=$store->store_id;
                    $domain->domainprefix=$this->_context->post('store_name');
                    $domain->domain=$domain->domainprefix.'.'.Q::ini('app_config/BASE_SHOP_DOMAIN');
                    $domain->save();
                }else{
                    $this->_view['error']['exist']=1;
                    break;
                }
                return $this->_redirect(url('/CreateStorestep2',array('store_id'=>$store->store_id)));
            }while(0);
        }
    }
    
    function actionCreateStorestep2(){
        //store 错误 
        $store=Stores::find('store_id=?',$this->_context->store_id)->getOne();
        if($store->isNewRecord()) die('Error no store');
        // 已经配置过 
        $sc=Store_Configs::find('store_id=?',$this->_context->store_id)->getOne();
        if(!$sc->isNewRecord()) die('Error exist');
        do{
            // currency
            $currency=Currencies::find('code=?',$store->currency)->getOne();
            $scurrency=Store_Currencies::find('store_id=? And code=?',$store->store_id,$store->currency)->getOne();
            $scurrency->store_id=$store->store_id;
            $scurrency->code=$currency->code;
            $scurrency->title=$currency->title;
            $scurrency->value=$currency->value;
            $scurrency->symbol_left=$currency->symbol_left;
            $scurrency->symbol_right=$currency->symbol_right;
            $scurrency->decimal_point=$currency->decimal_point;
            $scurrency->thousands_point=$currency->thousands_point;
            $scurrency->status=1;
            $scurrency->save();
            //language
            $l=Language::find('language=?',$store->language)->getOne();
            $sl=Store_Language::find('store_id=? And language=?',$store->store_id,$store->language)->getOne();
            $sl->store_id=$store->store_id;
            $sl->language=$l->language;
            $sl->title=$l->title;
            $sl->status=1;
            $sl->save();
            // 分类
            $c=Category::find('store_id=?',$store->store_id)->getOne();
            $c->store_id=$store->store_id;
            $c->name='First Category';
            $c->parent_id=0;
            $c->save();
            // 标签
            $t=new Taggoods();
            $t->tag_name='hot';
            $t->store_id=$store->store_id;
            $t->save();
            $t=new Taggoods();
            $t->tag_name='special';
            $t->store_id=$store->store_id;
            $t->save();
            // payment 
            // configs
            $sc=Configs::find()->getAll();
            foreach($sc as $s){
                $c=Store_Configs::find('store_id=? And config_key=?',$store->store_id,$s->config_key)->getOne();
                $c->config_key=$s->config_key;
                $c->value=$s->value;
                $c->store_id=$store->store_id;
                $c->save();
            }
            return $this->_redirect(url('/CreateStoreEnd',array('store'=>$store->name)));
            die('Success!');
        }while(0);
        die('Any Error ');
    }
    
    function actionCreateStoreEnd(){
        $domain='http://'.$this->_context->store.'.'.Q::ini('app_config/BASE_SHOP_DOMAIN');
        $url_store=$domain.url('default/index');
        $url_admin=$domain.url('storemanager/index');
        echo <<<EOF
    <p>
        创建成功 . <br>
        <a href="{$url_store}">店铺</a> <br> 
        
        <a href="{$url_admin}">后台</a>
    </p>    
EOF;
        die('');
    }
}

